﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Common;
using System.IO;
using Timer = System.Windows.Forms.Timer;

//using Timer = System.Windows.Forms.Timer;

namespace TaxiDispatchClient
{
    public partial class TaxiGPSHistoryForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiGPSHistoryForm()
        { 
            InitializeComponent();
            Init();
        }

        public TaxiGPSHistoryForm(DataRow row)
        {
            InitializeComponent();         

            label_phone.Text = row["手机号码"].ToString();
            buttonEdit_driver.Text = row["员工姓名"].ToString();
            label_name.Text = row["员工姓名"].ToString();
           
            label_gender.Text = "";
           
            label_workid.Text = "";
            label_lat.Text = "";
            label_lng.Text = "";
         
            label_time.Text = "";
            string sql = "phoneNumber='";
            sql += row["手机号码"].ToString();
            sql += "'";
            DataSet ds = MainForm.PositionService.DriverGetList(sql);
            if(ds!=null && ds.Tables[0].Rows.Count>0)
            {
                label_gender.Text = ds.Tables[0].Rows[0]["gender"].ToString();
                label_workid.Text = ds.Tables[0].Rows[0]["workid"].ToString();
            }
            Init();           
        }

        private GMapOverlay _overlay;
        private GMarkerGoogle _gMarker;
        private PointLatLng _point;
        private PointLatLng _prevpoint = new PointLatLng(0, 0);
        private DataTable _dttaxi;
        private DataTable _dtHistoryPoints;
        private int _countIndex;
        private int _markerIndex;
        //private int i=0;
        private readonly System.Windows.Forms.Timer _timerPerf = new Timer();
        System.Windows.Forms.Timer _timerPlayRoute;
        private void Init()
        {
            //--gMap
            const double theCenterLat = 30.55;
            const double theCenterLng = 114.29;
            gMap.Manager.Mode = AccessMode.ServerAndCache;
            gMap.MapProvider = GMapProviders.GoogleChinaMap;
            gMap.DragButton = MouseButtons.Left;
            _overlay = new GMapOverlay("overlay");
            gMap.Overlays.Add(_overlay);
            gMap.MaxZoom = 18;
            gMap.MinZoom = 10;
            gMap.Zoom = 12;
            gMap.Position = new PointLatLng(theCenterLat, theCenterLng);

            //--  trackBarControl_zoom 
            trackBarControl_zoom.Properties.Maximum = gMap.MaxZoom;
            trackBarControl_zoom.Properties.Minimum = gMap.MinZoom;
            trackBarControl_zoom.Value = (int)gMap.Zoom;

            //--dateEdit_date 
            dateEdit_date.DateTime = DateTime.Now;
            timeEdit_end.Time = DateTime.Now;
            DateTime startTime = DateTime.Now.AddHours(-6);
            timeEdit_start.Time = startTime;
            if (startTime.Date < DateTime.Today)
                timeEdit_start.Time = DateTime.Parse(
                    DateTime.Now.Date.ToString("yyyy-MM-dd ") + "00:00:00");            
        }

        private void gMap_OnMapZoomChanged()
        {
            trackBarControl_zoom.Value = (int)gMap.Zoom;
        }

        private void trackBarControl_zoom_ValueChanged(object sender, EventArgs e)
        {
            gMap.Zoom = trackBarControl_zoom.Value;
        }

        private void buttonEdit_driver_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (_timerPerf.Interval < 1000000)
            {
                _timerPerf.Interval = 10000000;
                _timerPerf.Stop();
            }

          
            _overlay.Markers.Clear();
            _overlay.Routes.Clear();
            _point.Lat = 0;
            _point.Lng = 0;

            btn_playBack.Enabled = false;
            btn_stop.Enabled = false;
            btn_download.Enabled = false;

            DriverInfoForm driverInfoForm = new DriverInfoForm();
            driverInfoForm.ShowDialog();
            if (driverInfoForm.gridView1.FocusedRowHandle >= 0)
            {
                DataRow row = driverInfoForm.gridView1.GetDataRow(driverInfoForm.gridView1.FocusedRowHandle);
                buttonEdit_driver.Text = row["Name"].ToString();
                label_phone.Text = row["PhoneNumber"].ToString();
                string strName = row["Name"].ToString();
                        
               
                label_name.Text = strName;                
                        
               
            }

        }

        private void simpleButton_select_Click(object sender, EventArgs e)
        {

            if (_timerPerf.Interval < 1000000)
            {
                _timerPerf.Interval = 10000000;
                _timerPerf.Stop();
            }
          

            btn_playBack.Enabled = false;
            btn_stop.Enabled = false;
            btn_download.Enabled = false;
            if (buttonEdit_driver.Text == "")
            {
                XtraMessageBox.Show("请选择想要查询的员工！");
                buttonEdit_driver.Focus();

                return;
            }
            if (timeEdit_start.Time > timeEdit_end.Time)
            {
                XtraMessageBox.Show("起始时间不能大于结束时间！");
                return;
            }
            label_notice.Text = "正在查询...";

            _overlay.Markers.Clear();
            _overlay.Routes.Clear();
            _point.Lat = 0;
            _point.Lng = 0;
            gMap.Zoom = 12;        
            pictureEdit_img.Visible = false;
            _markerIndex = 0;
            _dttaxi = null;

            label_lat.Text = "";
            label_lng.Text = "";
           
            label_time.Text = "";
            label_notice.Visible = true;

            Thread thread = new Thread(GetGpsList){IsBackground = true};
            thread.Start();
                    
            _prevpoint.Lat = 0;
            _prevpoint.Lng = 0;
            _timerPerf.Tick += DrawTaxiOnMap;
            _timerPerf.Enabled = true;
            _timerPerf.Interval = 2;
            _timerPerf.Start();

        }
        private void GetGpsList()
        {
           
            string strPhone = label_phone.Text;
            DateTime startTime = DateTime.Parse(
                dateEdit_date.DateTime.Date.ToString("yyyy-MM-dd") +" "
                + timeEdit_start.Time.ToString("HH:mm:ss"));
            DateTime endTime = DateTime.Parse(
                dateEdit_date.DateTime.Date.ToString("yyyy-MM-dd") + " "
                + timeEdit_end.Time.ToString("HH:mm:ss")); 
            try
            {
                DataSet ds = MainForm.PositionService.TaxiGpsHistoryGetList(strPhone, startTime, endTime);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    XtraMessageBox.Show("该员工在该时间段没有GPS位置记录！");
                    return;
                }
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_download.Enabled = true;
                }));              
                _dttaxi = ds.Tables[0];
                _countIndex = ds.Tables[0].Rows.Count;
                _dtHistoryPoints = ds.Tables[0].Copy();

                double lat = double.Parse(_dttaxi.Rows[0]["Latitude"].ToString());
                double lng = double.Parse(_dttaxi.Rows[0]["Longitude"].ToString());
                _point = new PointLatLng(lat, lng);
                DateTime time = DateTime.Parse(_dttaxi.Rows[0]["Updatetime"].ToString());
                int taxistate = int.Parse(_dttaxi.Rows[0]["Taxistate"].ToString());
                Bitmap obj = MainForm.GetTaxiBitmap(1);
                int id = int.Parse(_dttaxi.Rows[0]["id"].ToString());
                _gMarker = new GMarkerGoogle(_point, obj)
                {
                    ToolTipText =  "时间：" + time.ToString("HH:mm:ss") + Environment.NewLine,
                    ToolTipMode = MarkerTooltipMode.Always,
                    Tag = id
                };
                _overlay.Markers.Add(_gMarker);
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex, true);
                return;
            }
        }
        private void DrawTaxiOnMap(object sender, EventArgs eventArgs)
        {
            if(_dttaxi==null) return;
            int rowindex = _dttaxi.Rows.Count - 1;
            if (rowindex >= 0)
            {
                double lat = double.Parse(_dttaxi.Rows[rowindex]["Latitude"].ToString());
                double lng = double.Parse(_dttaxi.Rows[rowindex]["Longitude"].ToString());
                _point = new PointLatLng(lat, lng);
                int taxistate = int.Parse(_dttaxi.Rows[rowindex]["Taxistate"].ToString());
                if (Math.Abs(_prevpoint.Lat - 0) > 0)//------
                {
                    DrawLineBetweenTwoPoint(_prevpoint, _point, taxistate);
                }
                _dttaxi.Rows.Remove(_dttaxi.Rows[rowindex]);
                _prevpoint = _point;
                if (rowindex == _countIndex - 1)
                {
                    gMap.Position = _point;

                    label_lat.Text = _dttaxi.Rows[0]["Latitude"].ToString();
                    label_lng.Text =_dttaxi.Rows[0]["Longitude"].ToString();                  
                    label_time.Text =  _dttaxi.Rows[0]["Updatetime"].ToString();
                    int  state = int.Parse(_dttaxi.Rows[0]["Taxistate"].ToString());
                     
                }

            }
            else
            {

                btn_playBack.Enabled = true;
                btn_stop.Enabled = true;
                _timerPerf.Interval = 1000000;
                _timerPerf.Stop();
                label_notice.Text = "查询完毕";
            }
        }
        private void DrawLineBetweenTwoPoint(PointLatLng pointLatLng_S, PointLatLng pointLatLng_E, int state)
        {
            List<PointLatLng> points = new List<PointLatLng>();
            points.Add(pointLatLng_S);
            points.Add(pointLatLng_E);
            GMapRoute r = new GMapRoute(points, "");
            Pen pen = new Pen(Color.Green, 2);
            switch (state)
            {
                case 0:
                    pen.Color = Color.Green;
                    break;
                case 1:
                    pen.Color = Color.Blue;
                    break;
                case 2:
                    pen.Color = Color.Orange;
                    break;
                case 3:
                    pen.Color = Color.Gray;
                    break;
            }
            r.Stroke = pen;
            _overlay.Routes.Add(r);
        }

        private void gMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
        {
            pictureEdit_img.Image = null;
            var gMapMarker = (GMapMarker)item;
            string strTip = gMapMarker.ToolTipText;
            PointLatLng point = gMapMarker.Position;
            label_lat.Text = point.Lat.ToString() + "(纬)";
            label_lng.Text = point.Lng.ToString() + "(经)";
           
            label_time.Text = strTip.Substring(strTip.IndexOf("更新时间：") + 5, 8);
            string strWhere = "id=" + gMapMarker.Tag;
            try
            {
                DataSet ds = MainForm.PositionService.TaxiGpsHistoryGetListWhere(strWhere);
                if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["image"] != DBNull.Value)
                {
                    byte[] byteimg = (byte[])ds.Tables[0].Rows[0]["image"];
                    MemoryStream streamImg = new MemoryStream(byteimg);
                    Image image = Image.FromStream(streamImg, true);
                    pictureEdit_img.Image = ChangeImgSize(image, pictureEdit_img.Width, pictureEdit_img.Height);
                    pictureEdit_img.Visible = true;
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("GDI+"))
                {
                    XtraMessageBox.Show("该位置上传图片信息不完整，未能解析成功！");
                    return;
                }

                CommonRoutine.HandlingExceptions(ex, true);
                return;
            }
        }

        private void TaxiGPSHistoryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _timerPerf.Interval = 1000000;
            _timerPerf.Stop();
            if (_timerPlayRoute != null)
            {
                _timerPlayRoute.Interval = 10000000;
                _timerPlayRoute.Stop();
            }
        }

        private void pictureEdit_img_Click(object sender, EventArgs e)
        {
            if (pictureEdit_img.Image != null)
            {
                pictureEdit_bigImg.Image = ChangeImgSize(pictureEdit_img.Image, pictureEdit_bigImg.Width,
                    pictureEdit_bigImg.Height);
                pictureEdit_bigImg.Visible = true;

                // panel1.Enabled = false;
                gMap.Enabled = false;
                trackBarControl_zoom.Enabled = false;
            }
        }

        private Bitmap ChangeImgSize(Image image, int newwidth, int newheight)
        {
            Rectangle oldRectangle;
            Bitmap bmp;
            bmp = (Bitmap)image;
            oldRectangle = new Rectangle(0, 0, bmp.Width, bmp.Height);
            Bitmap tmpbmp = new Bitmap(newwidth, newheight);
            Graphics graphics = Graphics.FromImage(tmpbmp);
            Rectangle newRectangle = new Rectangle(0, 0, tmpbmp.Width, tmpbmp.Height);
            graphics.DrawImage(bmp, newRectangle, oldRectangle, GraphicsUnit.Pixel);
            graphics.Dispose();
            return tmpbmp;
        }

        private void pictureEdit_bigImg_DoubleClick(object sender, EventArgs e)
        {
            pictureEdit_bigImg.Image = null;
            pictureEdit_bigImg.Visible = false;
            gMap.Enabled = true;
            trackBarControl_zoom.Enabled = true;
        }

        //private void simpleButton1_Click(object sender, EventArgs e)
        //{
        //    double lat = 30.56;
        //    double lng = 114.28;
        //    DateTime time = DateTime.Parse("2012-2-28 00:11:11");
        //    string imagepath = @"E:\QQ.jpg";
        //    Image image = Image.FromFile(imagepath);
        //    byte[] byteImage = GetByteByImage(image);
        //    byte taxistate = byte.Parse("2");
        //    TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo
        //                                                {
        //                                                    Latitude = lat,
        //                                                    Longitude = lng,
        //                                                    DriverPhoneNumber = "13627264054",
        //                                                     Image = byteImage,
        //                                                    Taxistate = taxistate,
        //                                                    Time = time
        //                                                };
        //    MainForm.PositionService.AddTaxiGpsHistoryInfo(taxiGpsHistoryInfo);
        //    XtraMessageBox.Show("添加成功！");

        //}
        //private byte[] GetByteByImage(System.Drawing.Image image)
        //{
        //    MemoryStream memoryStream = new MemoryStream();
        //    image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
        //    byte[] byData = new Byte[memoryStream.Length];
        //    memoryStream.Position = 0;
        //    memoryStream.Read(byData, 0, byData.Length);
        //    memoryStream.Close();
        //    return byData;
        //}

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
      
        private void btn_playBack_Click(object sender, EventArgs e)
        {
            if (_timerPerf.Interval < 1000)
            {
                XtraMessageBox.Show("轨迹加载中，请等待！");
                return;
            }
            buttonEdit_driver.Enabled = false;
            btn_select.Enabled = false;
            int pointsCount = _dtHistoryPoints.Rows.Count;
            if (pointsCount == 0)
            {
                XtraMessageBox.Show("轨迹为空不能播放，请选择有记录的轨迹播放！");
                return;
            }        
            string strSpeed = imgComBoxEdit_playSpeed.Properties.Items
                [imgComBoxEdit_playSpeed.SelectedIndex].Value.ToString();

            _timerPlayRoute = new System.Windows.Forms.Timer();
            _timerPlayRoute.Tick += PlayRoute;
            _timerPlayRoute.Interval = int.Parse(strSpeed);
            _timerPlayRoute.Enabled = true;
            _timerPlayRoute.Start();
            btn_playBack.Enabled = false;
        }

        private void PlayRoute(object sender, EventArgs eventArgs)
        {     
            double lat = double.Parse(_dtHistoryPoints.Rows[_markerIndex]["Latitude"].ToString());
            double lng = double.Parse(_dtHistoryPoints.Rows[_markerIndex]["Longitude"].ToString());
            _point = new PointLatLng(lat, lng);
            DateTime time = DateTime.Parse(_dtHistoryPoints.Rows[_markerIndex]["Updatetime"].ToString());
            int taxistate = int.Parse(_dtHistoryPoints.Rows[_markerIndex]["Taxistate"].ToString());
            Bitmap obj = MainForm.GetTaxiBitmap(taxistate);
            _gMarker.Position = _point;
            _gMarker.ToolTipText =  "时间：" + time.ToString("HH:mm:ss") + Environment.NewLine;
            _gMarker.Bitmap = obj;
            Console.WriteLine(time.ToString());
            gMap.Refresh();
            if (_markerIndex < _dtHistoryPoints.Rows.Count - 1)
                _markerIndex++;
            else
            {
                _markerIndex = 0;
                _timerPlayRoute.Interval = 1000000;
                _timerPlayRoute.Stop();
                _timerPlayRoute.Dispose();
                BeginInvoke(new MethodInvoker(() =>
                {
                    buttonEdit_driver.Enabled = true;
                    btn_select.Enabled = true;
                    btn_playBack.Enabled = true;
                }));
            }
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            btn_playBack.Enabled = true;
            _timerPlayRoute.Interval = 100000000;
            _timerPlayRoute.Stop();
            buttonEdit_driver.Enabled = true;
            btn_select.Enabled = true;
        }

        private void btn_download_Click(object sender, EventArgs e)
        {
            if (_dtHistoryPoints.Rows.Count == 0)
            {
                XtraMessageBox.Show("请先选择轨迹！");
                return;
            }
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "Google地图轨迹(*.kml)|所有文件(*.*)";
            saveFile.ShowDialog();
            if (saveFile.FileName.Trim() == "") return;
            string filename = saveFile.FileName + ".kml";
            // Create the file and writer.
            FileStream fs = new FileStream(filename, FileMode.Create);
            XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
            // Start the document.
            w.WriteStartDocument();
            w.WriteStartElement("kml", "http://earth.google.com/kml/2.1");
            w.WriteStartElement("Document");
            w.WriteStartElement("name");
            w.WriteString(filename);
            w.WriteEndElement();
            w.WriteStartElement("open");
            w.WriteString("1");
            w.WriteEndElement();
            //style
            w.WriteStartElement("Style");
            w.WriteAttributeString("id", "normalPlacemark");
            w.WriteStartElement("IconStyle");
            w.WriteStartElement("Icon");
            w.WriteStartElement("href");
            w.WriteString("F:/img/aws0.gif");
            w.WriteEndElement();//style
            w.WriteEndElement();//iconStyle
            w.WriteEndElement();//icon
            w.WriteEndElement();//href

            //stylemap
            w.WriteStartElement("StyleMap");
            w.WriteAttributeString("id", "exampleStyleMap");
            w.WriteStartElement("Pair");
            w.WriteStartElement("key");
            w.WriteString("normal");
            w.WriteEndElement();
            w.WriteStartElement("styleUrl");
            w.WriteString("#normalPlacemark");
            w.WriteEndElement();//styleUrl
            w.WriteEndElement();//pair
            w.WriteEndElement();//StyleMap


            w.WriteStartElement("Placemark");
            w.WriteStartElement("Name");
            w.WriteString(filename);
            w.WriteEndElement();
            //write styleurl
            w.WriteStartElement("styleUrl");
            w.WriteString("#exampleStyleMap");
            w.WriteEndElement();


            // Write Point element
            w.WriteStartElement("LineString");
            w.WriteStartElement("coordinates");
            string points = "";
            for (int i = 0; i < _dtHistoryPoints.Rows.Count; i++)
            {
                string lng = _dtHistoryPoints.Rows[i]["Longitude"].ToString();
                string lat = _dtHistoryPoints.Rows[i]["Latitude"].ToString();
                //double dlat = double.Parse(lat) - 0.212164;
                //double dlng = double.Parse(lng) - 0.166551;
                //lat = dlat.ToString();
                //lng = dlng.ToString();
                points += lng + "," + lat + ",0 ";
            }
            w.WriteString(points);
            w.WriteEndElement();
            w.WriteEndElement();

            w.WriteEndElement(); // Placemark
            w.WriteEndElement();//document
            w.WriteEndElement(); // kml

            // Ends the document.
            w.WriteEndDocument();

            // close writer
            w.Close();

            XtraMessageBox.Show("保存成功！");
        }

      


    }
}